/**
 * 路由配置
 */
import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      component: () => import('@/layouts/MainLayout.vue'),
      meta: { requiresAuth: true },
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/Dashboard.vue'),
          meta: { title: '数据概览' }
        },
        {
          path: 'users',
          name: 'AdminUsers',
          component: () => import('@/views/AdminUsers.vue'),
          meta: { title: '用户管理', permission: 'admin_user:view' }
        },
        {
          path: 'roles',
          name: 'Roles',
          component: () => import('@/views/Roles.vue'),
          meta: { title: '角色管理', permission: 'role:view' }
        },
        {
          path: 'resources',
          name: 'Resources',
          component: () => import('@/views/Resources.vue'),
          meta: { title: '资源管理', permission: 'resource:view' }
        },
        {
          path: 'business/users',
          name: 'BusinessUsers',
          component: () => import('@/views/BusinessUsers.vue'),
          meta: { title: '用户端用户', permission: 'business:user:view' }
        },
        {
          path: 'business/training',
          name: 'TrainingRecords',
          component: () => import('@/views/TrainingRecords.vue'),
          meta: { title: '训练记录', permission: 'business:training:view' }
        },
        {
          path: 'business/verifications',
          name: 'Verifications',
          component: () => import('@/views/Verifications.vue'),
          meta: { title: '实名认证', permission: 'business:verification:view' }
        },
        {
          path: 'logs',
          name: 'OperationLogs',
          component: () => import('@/views/OperationLogs.vue'),
          meta: { title: '操作日志', permission: 'log:view' }
        },
        {
          path: 'customer-service',
          name: 'CustomerService',
          component: () => import('@/views/CustomerService.vue'),
          meta: { title: '客服管理', permission: 'customer_service:view' }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = localStorage.getItem('admin_access_token')

  // 需要认证的路由
  if (to.meta.requiresAuth !== false) {
    if (!token) {
      next('/login')
      return
    }

    // 检查权限
    if (to.meta.permission) {
      if (!userStore.hasPermission(to.meta.permission)) {
        next('/dashboard')
        return
      }
    }
  }

  // 已登录访问登录页，跳转到首页
  if (to.path === '/login' && token) {
    next('/')
    return
  }

  next()
})

export default router
